//
//  GoodsClassifyVC.m
//  phmall
//
//  Created by admin on 2017/10/15.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "GoodsClassifyVC.h"
#import "ClassifyView.h"
#import "GoodsListCell.h"
#import "SequencingView.h"
#import "GoodsModel.h"
#import "CommodityDetailsVC.h"
@interface GoodsClassifyVC ()<UICollectionViewDelegate,UICollectionViewDataSource,GoodsListCellDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>{
    NSInteger    start;
    NSInteger    count;
}
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *goodsArray;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation GoodsClassifyVC
-(void)moreAction:(UICollectionViewCell *)cell{
    for (int i=0; i<5; i++) {
        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
        GoodsListCell *goodsCell=(GoodsListCell *)[self.collectionView cellForItemAtIndexPath:index1];
        if (cell!=goodsCell) {
            [goodsCell moreViewTapAction];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.emptyType=EmptyDataSetNone;
    start=0;
    count=0;
    [self loadDataWithGet_goods];
    [self setUI];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
    self.collectionView.mj_footer.hidden=YES;

    // Do any additional setup after loading the view.
}

-(void)HeaderRefresh{
    start=0;
    [self loadDataWithGet_goods];
}
-(void)footeRefresh{
    start=self.goodsArray.count;
    if (start<count) {
        [self loadDataWithGet_goods];
    }else{
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    }
    
    
}
-(void)rightBarAction{
    
}
- (void)loadDataWithGet_goods{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"category/get_goods"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:[NSString stringWithFormat:@"%ld",(long)start] forKey:@"start"];
    [parametersDic setObject:self.uid forKey:@"cat"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.goodsArray removeAllObjects];
            self.collectionView.mj_footer.hidden=YES;
        }
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            count=[responseDict[@"count"] intValue];
            NSMutableArray *goods=responseDict[@"data"];
            [self  analysisDataWithIndexDictionary:goods];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.collectionView.mj_footer.hidden=YES;
        [self.goodsArray removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)analysisDataWithIndexDictionary:(NSMutableArray *)array{
    [self.goodsArray removeAllObjects];
    for (NSMutableDictionary *dict in array) {
        GoodsModel *model = [GoodsModel yy_modelWithDictionary:dict];
        [self.goodsArray addObject:model];
    }

    if (self.goodsArray.count!=0) {
        
        //数量少于2条时隐藏上拉加载
        if (self.goodsArray.count<2) {
            self.collectionView.mj_footer.hidden=YES;
        }else{
            self.collectionView.mj_footer.hidden=NO;
        }
    }else{
        //数量为0条时隐藏上拉加载
        self.collectionView.mj_footer.hidden=YES;
    }
    [self.collectionView reloadData];
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}
-(void)setUI{
    
    UIBarButtonItem *rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:Localized(@"更多")] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIBarButtonItem *leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"NavBar_backImg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(0);
    }];


}

#pragma mark collectionView代理方法

//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //    NSMutableArray *goodsArr=self.timeArr[section];
    return self.goodsArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"cell";
    GoodsListCell *cell = (GoodsListCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.delegate=self;
    GoodsModel *model=self.goodsArray[indexPath.row];
    cell.model=model;
    ViewBorderRadius(cell, 10, 0, [UIColor clearColor]);
    return cell;
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (iPhone5SE) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 230);
    }else  if (iPhone6_6s) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }else  if (iPhone6Plus_6sPlus) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 272);
    }else{
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }
}
//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 0, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    for (int i=0; i<self.goodsArray.count; i++) {
        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
        GoodsListCell *cell =  (GoodsListCell *)[_collectionView cellForItemAtIndexPath:index1];
        [cell moreViewTapAction];
    }
    GoodsModel *model=self.goodsArray[indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectRowAtIndexPath:)]) {
        [self.delegate didSelectRowAtIndexPath:model.uid];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"分类缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -(self.tabBar_height+49+44)/2;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"当前分类暂无信息！"),Localized(@"先去其他地方逛逛吧。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"当前分类暂无信息！") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"当前分类暂无信息！") length], [Localized(@"先去其他地方逛逛吧。") length])];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
}

#pragma mark - DZNEmptyDataSetDelegate
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithGet_goods];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.collectionView.contentOffset = CGPointZero;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //2.初始化collectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[GoodsListCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.showsVerticalScrollIndicator=NO;
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
//        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyDataSetDelegate=self;
        _collectionView.emptyDataSetSource=self;
    }
    return _collectionView;
}
-(NSMutableArray *)goodsArray{
    if (!_goodsArray) {
        _goodsArray=[[NSMutableArray alloc]init];
    }
    return _goodsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
